import utils.DataUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: Assembler
 * @Description: TODO
 * @author: DJ008854
 * @date: 2020年10月27日 20:18
 */
public class Assembler {

    public Map<Integer,String> instructions = new HashMap<>();
    public Map<String,Integer> labelMap = new HashMap<>();
    public Map<String,Integer> wordMap = new HashMap<>();

    public String assemble(){
        InstructionLoader instructionLoader = new InstructionLoader();
        List<String> validLines = instructionLoader.loadIns();
        InstrctionsPretreater instrctionsPretreater = new InstrctionsPretreater();
        List<String> instructionLines = instrctionsPretreater.pretreat(validLines);
        String binCodes = "";
        String hexCodes = "";
        for(int i=0;i<instructionLines.size();i++){
            String instruction = instructionLines.get(i);
            int instructionNum = i;
            InstructionsDecoder instructionsDecoder =  new InstructionsDecoder(instrctionsPretreater,instructionNum);
            System.out.println(Long.toString(instructionNum,16));
            System.out.println(instruction);

            String binCode = instructionsDecoder.decodeInstruction(instruction);
            String hexCode = DataUtils.binaryStr2HexStr(binCode,8);
            System.out.println(hexCode);
            hexCodes += " "+hexCode;
            System.out.println(binCode);
            binCodes += binCode+"\n";
            System.out.println("-----------");
            instructionNum ++;
        }
        System.out.println("labels:");
        for(String label:instrctionsPretreater.labelMap.keySet()){
            String num = Long.toString(instrctionsPretreater.labelMap.get(label),16);
            System.out.println(label+":"+num);
        }
        System.out.println(hexCodes);
        return binCodes;
    }

    private String cleanEndLineAnnotation(String content){
        int index = content.indexOf("//");
        if(index == -1){
            return content;
        }
        content = content.substring(0,index);
        return content;
    }

    private void parseWord(String content){
        String[] segments = content.trim().split(" ");
        wordMap.put(segments[0], Integer.parseInt(segments[2]));
    }

}
